﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;

namespace Controllers
{
    public class ConexionBaseDeDatos
    {
        private static OleDbConnection conn = new OleDbConnection();

        public static OleDbConnection GetConnection()
        {
            try
            {
                if (conn.State == ConnectionState.Closed)
                {
                    conn.ConnectionString = @"Provider=SQLOLEDB.1;Persist Security Info=False;User ID=gd;Initial Catalog=GD1C2012;Data Source=localhost\SQLEXPRESS;Password=gd2012";
                    conn.Open();
                }
                return conn;
            }
            catch (Exception ex)
            {
                throw ex;
            }


        }

        public static OleDbDataReader GetData(string texto, CommandType tipo)
        {
            var comando = new OleDbCommand
            {
                Connection = GetConnection(),
                CommandText = texto,
                CommandType = tipo,

            };

            return comando.ExecuteReader();
        }


        public static OleDbDataReader GetData(string texto, CommandType tipo, OleDbTransaction trans)
        {
            var comando = new OleDbCommand
            {
                Connection = trans.Connection,
                CommandText = texto,
                CommandType = tipo,
                Transaction =  trans
            };

            return comando.ExecuteReader();
        }


        public static void Guardar(string texto, CommandType tipo)
        {
            var comando = new OleDbCommand
            {
                Connection = GetConnection(),
                CommandText = texto,
                CommandType = tipo
            };

            comando.ExecuteNonQuery();
        }


        public static OleDbTransaction Guardar(string texto, CommandType tipo, OleDbTransaction trans)
        {

            var comando = new OleDbCommand
                              {
                                  Connection = trans.Connection,
                                  CommandText = texto,
                                  CommandType = tipo,
                                  Transaction = trans
                              };

            comando.ExecuteNonQuery();

            return trans;
        }

        public static int ObtenerUltimoAgregado(OleDbTransaction trans)
        {
            const string sql = "SELECT @@IDENTITY AS Id";
            var reader = GetData(sql, CommandType.Text, trans);
            if (reader.HasRows)
            {
                reader.Read();

                return Convert.ToInt32(reader["Id"]);
            }
            throw new Exception("error al obtener id");
        }

    }
}
